package org.marsdonne.auth.resolver;

import graphql.kickstart.tools.GraphQLMutationResolver;
import graphql.schema.DataFetchingEnvironment;
import org.marsdonne.auth.AuthUtils;
import org.marsdonne.auth.EndPointUser;
import org.marsdonne.auth.EndPointUserRepos;
import org.marsdonne.auth.UnionUser;
import org.marsdonne.commons.oss.ObjectStorable;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.Part;
import java.io.IOException;
import java.util.List;

@Component
public class UserMutationResolver implements GraphQLMutationResolver {

    @Resource
    private EndPointUserRepos endPointUserRepos;

    @Resource
    private ObjectStorable objectStorable;

    public UnionUser certify(String residentId, String realName) {
        String identifier = AuthUtils.getCurrentUser().getUsername();
        return endPointUserRepos.certifyUser(identifier, residentId, realName);
    }

    public EndPointUser updateAvatar(List<Part> parts, DataFetchingEnvironment dataFetchingEnvironment) {
        String identifier = AuthUtils.getCurrentUser().getUsername();

        List<Part> uploadImages = dataFetchingEnvironment.getArgument("uploadImages");

        EndPointUser endPointUser = null;

        try {
            endPointUser = this.endPointUserRepos.updateAvatarUrl(
                    identifier, objectStorable.upload(
                            ObjectStorable.Space.InfoShows, ObjectStorable.Category.Avatar, uploadImages.get(0).getInputStream()
                    )).orElse(null);
        } catch (IOException exception) {
            exception.printStackTrace();
        }

        return endPointUser;
    }

    public EndPointUser updateNickname(String nickname) {
        String identifier = AuthUtils.getCurrentUser().getUsername();

        return this.endPointUserRepos.updateNickname(identifier, nickname).orElse(null);
    }
}
